<template>
  <div>
    <slot name="paper" :content="content"></slot>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, watch, onBeforeUnmount } from "vue";

const props = defineProps({
  //内容
  printerInfo: {
    type: String,
    default: "",
  },
  //速度
  duration: {
    type: Number,
    default: 100,
  },
  //延迟
  delay: {
    type: Number,
    default: 3000,
  },
  working: {
    type: Boolean,
    default: true,
  },
  once: {
    type: Boolean,
    default: false,
  },
});
const content = ref("");
const cursor = ref(0);
const timer = ref(null);
const timeout = ref(null);
const print = ref(true);

onMounted(() => {
  if (props.working) {
    start(work);
  } else {
    content.value = props.printerInfo;
  }
});

// 监听 working 和 printerInfo 的变化
watch([() => props.working, () => props.printerInfo], () => {
  toBegin();
});

// 监听 cursor 的变化
watch(cursor, (newCursor) => {
  content.value = props.printerInfo.slice(0, newCursor);
});


// 在组件卸载前执行
onBeforeUnmount(() => {
  clearInterval(timer);
});

/**
 * 定时
 */
const start = () => {
  timeout.value = setTimeout(() => {
    timer.value = setInterval(() => {
      work();
      if (
        cursor.value === 0 ||
        (cursor.value === props.printerInfo.length && !props.once)
      ) {
        clearInterval(timer.value);
        start(work);
      } else if (cursor.value === props.printerInfo.length && props.once) {
        clearInterval(timer.value);
      }
    }, props.duration);
  }, props.delay);
};
/**
 * 逻辑
 */
const work = () => {
  let currentCursor = cursor.value;
  currentCursor += print.value ? 1 : -1;
  if (print.value) {
    if (currentCursor === props.printerInfo.length + 1) {
      currentCursor -= 2;
      print.value = !print.value;
    }
  } else {
    if (currentCursor === -1) {
      currentCursor += 2;
      print.value = !print.value;
    }
  }
  cursor.value = currentCursor;
};
const toBegin = () => {
  cursor.value = 0;
  if (timeout.value !== null) {
    clearTimeout(timeout.value);
    if (timer.value !== null) {
      clearInterval(timer.value);
    }
  }
  if (props.working) {
    start(work);
  } else {
    content.value = props.printerInfo;
  }
};
</script>
